from flask import Flask, redirect, url_for, request,Response,render_template,send_file
from flask_cors import CORS
from picamera import PiCamera
import json
import pwm
import time

#建立flask app
app=Flask(__name__)
#建立小车对象
car=pwm.CarMove()
speed=50
#将响应函数关联到网络地址
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/control',methods=['POST','GET'])
def car_control():
    #加载前端传回的json数据，转换成字典类型
    dic=request.args
    #将字典中的参数分别提取出来以供函数调用
    speed=int(dic['speed'])
    theta=int(dic['theta'])
    # if car.get_dis()<0.2 and speed>0:
    #     return
    print(speed,theta)
    pwm.control(speed,theta,car)
    return json.dumps(dic)

@app.route('/control/',methods=['POST','GET'])
def car_controll():
    #加载前端传回的json数据，转换成字典类型
    dic=request.args
    #将字典中的参数分别提取出来以供函数调用
    control=int(dic['control'])
    if (control == 0):
        pwm.stop(car)
        print("停止")
        return json.dumps(dic)
    elif(control == 1):
        #car.()
        print("自动控制中")
        return json.dumps(dic)
    elif(control == 2):
        pwm.control(speed,0,car)
        print("前进")
        return json.dumps(dic)
    elif(control == 3):
        pwm.control(speed,-90,car)
        print("左转")
        return json.dumps(dic)
    elif(control == 4):
        pwm.control(speed,90,car)
        print("右转")
        return json.dumps(dic)
    elif(control == 5):
        pwm.control(-1*speed,0,car)
        print("后退")
        return json.dumps(dic)
    else:
        return json.dumps(dic)

@app.route('/run/',methods=['POST','GET'])
def run():
    #加载前端传回的json数据，转换成字典类型
    dic=request.args
    #将字典中的参数分别提取出来以供函数调用
    if (dic['speed'] == ""):
        return json.dumps("启动失败")
    else:
        speed=int(dic['speed'])
        theta=int(dic['theta'])
        pwm.control(speed,theta,car)
        print(speed,theta)
        return json.dumps("启动成功")

@app.route('/stop',methods=['POST','GET'])
def car_stop():
    pwm.stop(car)
    return request.get_data()


if __name__ == "__main__":
    #允许跨域访问
    #CORS(app,resources=r'/*')
    app.run(host='0.0.0.0',threaded=True)